<template>
  <div class="home-container">
    <el-row :gutter="20">
      <!-- 左侧系统状态 -->
      <el-col :span="8">
        <el-card class="status-card">
          <template #header>
            <div class="card-header">
              <span>系统状态</span>
              <el-tag type="success">运行正常</el-tag>
            </div>
          </template>
          
          <div class="status-list">
            <div class="status-item">
              <span class="status-label">AI引擎</span>
              <el-tag type="success">运行正常</el-tag>
            </div>
            <div class="status-item">
              <span class="status-label">语音识别</span>
              <el-tag type="success">已连接</el-tag>
            </div>
            <div class="status-item">
              <span class="status-label">知识库</span>
              <el-tag type="success">正常</el-tag>
            </div>
            <div class="status-item">
              <span class="status-label">数字人</span>
              <el-tag type="success">在线</el-tag>
            </div>
          </div>
        </el-card>
        
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>使用统计</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ stats.totalQuestions }}</div>
                <div class="stat-label">总问题数</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ stats.accuracy }}</div>
                <div class="stat-label">准确率</div>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ stats.responseTime }}</div>
                <div class="stat-label">平均响应时间</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ stats.satisfaction }}</div>
                <div class="stat-label">满意度</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      
      <!-- 右侧数字人对话 -->
      <el-col :span="16">
        <el-card class="chat-card">
          <template #header>
            <div class="card-header">
              <div class="avatar-info">
                <div class="avatar-preview" :class="getAvatarClass()">
                  <div class="avatar-face">
                    <div class="avatar-eyes" :class="getExpressionClass()"></div>
                    <div class="avatar-mouth" :class="getExpressionClass()"></div>
                  </div>
                </div>
                <div class="avatar-details">
                  <div class="avatar-name">{{ getProfessionText() }}</div>
                  <div class="avatar-status">在线</div>
                </div>
              </div>
              <div class="chat-controls">
                <el-button type="primary" size="small" @click="handleVoiceToggle">
                  <el-icon><Microphone /></el-icon>
                  {{ isListening ? '停止' : '语音' }}
                </el-button>
                <el-button size="small" @click="handleClearChat">
                  <el-icon><Delete /></el-icon>
                  清空
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="chat-container">
            <div class="chat-messages" ref="chatMessages">
              <div 
                v-for="(message, index) in chatHistory" 
                :key="index" 
                :class="['message', message.type]">
                <div class="message-avatar" v-if="message.type === 'ai'">
                  <div class="avatar-face small">
                    <div class="avatar-eyes" :class="getExpressionClass()"></div>
                    <div class="avatar-mouth" :class="getExpressionClass()"></div>
                  </div>
                </div>
                <div class="message-content">
                  <div class="message-text">{{ message.content }}</div>
                  <div class="message-time">{{ message.time }}</div>
                </div>
                <div class="message-avatar user" v-if="message.type === 'user'">
                  <el-icon><User /></el-icon>
                </div>
              </div>
            </div>
            
            <div class="chat-input">
              <el-input
                v-model="inputMessage"
                placeholder="请输入您的问题..."
                @keyup.enter="handleSendMessage"
                :disabled="isProcessing">
                <template #append>
                  <el-button 
                    type="primary" 
                    @click="handleSendMessage"
                    :disabled="!inputMessage.trim() || isProcessing">
                    <el-icon><ChatDotRound /></el-icon>
                    发送
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { Microphone, ChatDotRound, User, Delete } from '@element-plus/icons-vue'
import { useAppStore } from '../stores'
import { ElMessage } from 'element-plus'

const store = useAppStore()

// 聊天相关
const inputMessage = ref('')
const isProcessing = ref(false)
const isListening = ref(false)
const chatMessages = ref(null)

// 统计数据
const stats = reactive({
  totalQuestions: 156,
  accuracy: '98.5%',
  responseTime: '1.2s',
  satisfaction: '4.8/5'
})

// 聊天历史
const chatHistory = ref([
  {
    type: 'ai',
    content: '您好！我是您的AI数字人助手。我可以帮助您解答工程相关的问题，包括土建、机电、装修、市政等各个领域的专业知识。请问有什么可以帮助您的吗？',
    time: new Date().toLocaleTimeString()
  }
])

// 获取数字人设置
const avatarSettings = computed(() => store.avatarSettings)

// 获取数字人CSS类
const getAvatarClass = () => {
  return `avatar-${avatarSettings.value.type}-${avatarSettings.value.gender}`
}

// 获取表情CSS类
const getExpressionClass = () => {
  return `expression-${avatarSettings.value.expression}`
}

// 获取专业文本
const getProfessionText = () => {
  const professions = {
    engineer: '资深工程师',
    technician: '年轻技术员',
    architect: '建筑师',
    consultant: '专业顾问'
  }
  return professions[avatarSettings.value.type] || 'AI助手'
}

// 发送消息
const handleSendMessage = async () => {
  if (!inputMessage.value.trim() || isProcessing.value) return
  
  const userMessage = inputMessage.value.trim()
  
  // 添加用户消息
  chatHistory.value.push({
    type: 'user',
    content: userMessage,
    time: new Date().toLocaleTimeString()
  })
  
  inputMessage.value = ''
  isProcessing.value = true
  
  // 滚动到底部
  await nextTick()
  scrollToBottom()
  
  // 模拟AI回复
  setTimeout(() => {
    const aiResponse = generateAIResponse(userMessage)
    chatHistory.value.push({
      type: 'ai',
      content: aiResponse,
      time: new Date().toLocaleTimeString()
    })
    
    isProcessing.value = false
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  }, 1000)
}

// 生成AI回复
const generateAIResponse = (message) => {
  // 检查是否是问题或关键词
  const isQuestion = message.includes('?') || message.includes('？') || 
                    message.includes('什么') || message.includes('如何') || 
                    message.includes('怎么') || message.includes('为什么') ||
                    message.includes('基础') || message.includes('施工') ||
                    message.includes('结构') || message.includes('设计') ||
                    message.includes('机电') || message.includes('设备') ||
                    message.includes('装修') || message.includes('市政') ||
                    message.includes('工程') || message.includes('技术')
  
  // 如果不是问题，给出友好的回应
  if (!isQuestion) {
    const friendlyResponses = [
      `您好！我看到您发送了"${message}"。我是您的AI工程助手，专门解答工程相关的问题。如果您有任何关于土建、机电、装修、市政等工程方面的问题，我很乐意为您提供专业的解答。`,
      `"${message}" - 我注意到您发送了这个内容。作为您的工程助手，我可以帮助您解答各种工程问题。请随时向我提问！`,
      `收到您的消息"${message}"。如果您有工程相关的问题需要咨询，比如施工技术、设计规范、设备选型等，我都可以为您提供专业的建议。`
    ]
    return friendlyResponses[Math.floor(Math.random() * friendlyResponses.length)]
  }
  
  // 如果是问题，给出专业回答
  if (message.includes('基础') || message.includes('施工')) {
    return '关于基础施工的问题，需要特别注意地质条件、荷载计算和施工工艺。建议您查看相关的施工规范和标准，确保施工质量和安全。'
  } else if (message.includes('结构') || message.includes('设计')) {
    return '结构设计是工程的核心环节，需要考虑荷载、材料、构造等多个方面。建议您咨询专业的结构工程师，确保设计方案的合理性。'
  } else if (message.includes('机电') || message.includes('设备')) {
    return '机电设备的选择和安装需要综合考虑系统性能、维护便利性和成本效益。建议您根据具体需求选择合适的设备型号和安装方案。'
  } else if (message.includes('装修') || message.includes('装饰')) {
    return '装修工程需要考虑材料选择、施工工艺、环保要求等多个方面。建议您根据使用功能和预算要求，选择合适的装修方案。'
  } else if (message.includes('市政') || message.includes('道路')) {
    return '市政工程涉及道路、桥梁、管网等多个专业。需要综合考虑交通流量、地质条件、环境影响等因素，确保工程质量和安全。'
  } else {
    const professionalResponses = [
      '这是一个很好的工程问题！根据我的专业知识，我可以为您提供详细的解答。',
      '您提到的这个问题在工程实践中确实很重要，让我为您详细分析一下。',
      '根据相关的技术规范和标准，我建议您考虑以下几个方面...',
      '这个问题涉及到多个技术要点，我来为您逐一解释。',
      '从工程安全的角度来看，这个问题需要特别注意...',
      '根据最新的技术发展趋势，我建议您采用以下方案...'
    ]
    return professionalResponses[Math.floor(Math.random() * professionalResponses.length)]
  }
}

// 语音切换
const handleVoiceToggle = () => {
  isListening.value = !isListening.value
  ElMessage.success(isListening.value ? '语音识别已开启' : '语音识别已关闭')
}

// 清空聊天
const handleClearChat = () => {
  chatHistory.value = [{
    type: 'ai',
    content: '聊天记录已清空。请问有什么可以帮助您的吗？',
    time: new Date().toLocaleTimeString()
  }]
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatMessages.value) {
    chatMessages.value.scrollTop = chatMessages.value.scrollHeight
  }
}

// 初始化
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.status-card,
.stats-card,
.chat-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-weight: 500;
  color: #333;
}

.stat-item {
  text-align: center;
  padding: 15px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.avatar-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar-preview {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #409eff;
}

.avatar-face.small {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #f0f0f0;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.avatar-eyes {
  width: 20px;
  height: 10px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.avatar-eyes::before,
.avatar-eyes::after {
  content: '';
  width: 4px;
  height: 4px;
  background: #333;
  border-radius: 50%;
}

.avatar-mouth {
  width: 10px;
  height: 5px;
  border: 1px solid #333;
  border-top: none;
  border-radius: 0 0 10px 10px;
}

.avatar-details {
  display: flex;
  flex-direction: column;
}

.avatar-name {
  font-weight: 500;
  color: #333;
}

.avatar-status {
  font-size: 12px;
  color: #67c23a;
}

.chat-controls {
  display: flex;
  gap: 10px;
}

.chat-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 15px;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  gap: 10px;
}

.message.user {
  flex-direction: row;
  justify-content: flex-end;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.message-avatar.user {
  background: #409eff;
  color: #fff;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message.user .message-content {
  align-items: flex-end;
  order: -1;
}

.message-text {
  background: #fff;
  padding: 10px 15px;
  border-radius: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  word-wrap: break-word;
  display: inline-block;
  max-width: 100%;
}

.message.user .message-text {
  background: #409eff;
  color: #fff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.message.user .message-time {
  text-align: right;
}

.chat-input {
  padding: 10px 0;
}

/* 表情样式 */
.expression-thinking .avatar-eyes::before,
.expression-thinking .avatar-eyes::after {
  background: #666;
  transform: scale(0.8);
}

.expression-explaining .avatar-mouth {
  width: 12px;
  height: 6px;
  border-radius: 0 0 12px 12px;
}

.expression-smiling .avatar-mouth {
  width: 8px;
  height: 4px;
  border-radius: 50%;
  border: 1px solid #333;
}

.expression-serious .avatar-eyes::before,
.expression-serious .avatar-eyes::after {
  background: #000;
  transform: scale(1.2);
}

.expression-happy .avatar-eyes::before,
.expression-happy .avatar-eyes::after {
  background: #ff6b6b;
}
</style>